<?php

class Kit_Controller extends WakEngineController {

    function _setUp() {
        $id=$this->response->shiftNode();
        // gettign kit
        if (!$this->kit=Webappkit::getKit($id)) {
            throw new WakEngineErrorPage("kit not found",404);
            return false;
        }
        $this->response->kit=$this->kit;
        $this->response->cfg=$this->kit->getCfg();
    }

    /**
     *
     */
    function index() {

        $kit=&$this->kit;
        $this->response->subkits=$kit->listSubkits(); //print_r($this->subkits);
        // is there a unit tests directory ?
        $this->response->tests=is_dir($kit->getpath().'tests');
        // is there some doc ?
        if (is_file($kit->getpath().'docs/index.rest.txt')) {
            $txt=join('',file($kit->getpath().'docs/index.rest.txt')); // echo '<pre>'.$txt;
            webappkit::getkit('text_rest');
            $tree=text_rest::parse($txt);
            $formatter=Text_reST_Formatter::factory('html');
            $this->response->doc=$formatter->format($tree);
            // echo '<pre>'; print_r($doc);
        } else $this->response->doc=null;
    }

    function tests() {
        return $this->_runKitTests($this->response->kit);
    }

    /**
     * executes a kit's embedded unit tests
     * @param Webappkit $kit
     */
    function _runKitTests(& $kit) {
        // loading simple test framework
        $ST=Webappkit::getKit('simpletest');
        // searching for test cases
        $path=$kit->getPath().'tests/';
        if (!$d=dir($path))
            return false;
        while ($file=$d->read()) {
            $file=$path.$file;
            if (!is_file($file) or substr($file,-4)!='.php')
                continue;
            // echo "<p>$file</p>";
            include($file);
        }
        // running test cases
        $this->_runAllTestClasses("unit tests for ".$kit->getid());
        return true;
    }

    function _runAllTestClasses($label='All test classes') {
		$group=new GroupTest($label);
		// searching for all declared test classes
		$classes=get_declared_classes();
		foreach ($classes as $class) {
			if (strtolower(substr($class,0,4))!='test')
				continue;
			// adding class to group test
			$group->addTestClass($class);
		}
		// running group test
		$group->run(new HtmlReporter());
		// print_r($group);
	}
}
?>